
Problem statement:Writa a YACC specification to check syntax of "switch? case" statement of 'C' language.


---------------------------------------------------------------------
Yacc File:

%{
#include <stdio.h>
#include <stdlib.h>
%}

%token character NUM SWITCH CASE DEFAULT BREAK LE GE EQ NE OR AND GT LT ADD SUB MUL DIV
%right '='
%left AND OR
%left GT LT LE GE EQ NE
%left ADD SUB
%right MUL DIV
%%

S       : ST {printf("Input accepted.\n");exit(0);}
         ;
ST     :    SWITCH '(' character ')' '{' B '}'
         ;
   
B       :    C
         |    C    D
        ;
   
C      :    C    C
        |    CASE NUM ':' E ';'
        | BREAK ';'
        ;

D      :    DEFAULT    ':' E ';' BREAK ';'
        ;
    
E    : character'='E
    | E ADD E
    | E SUB E
    | E MUL E
    | E DIV E
    | E LT E
    | E GT E
    | E LE E
    | E GE E
    | E EQ E
    | E NE E
    | E OR E
    | E AND E
    | character
    | NUM
    ;

%%

#include "lex.yy.c"

main()
{
printf("Enter the expression: ");
yyparse();
}



------------------------------------------------
Lex File:

char [A-Za-z]
digit [0-9]
%%
[ \t\n]  
switch return SWITCH;
case return CASE;
break return BREAK;
default return DEFAULT;
{digit}+ return NUM;
{char}({char}|{char})* return character;
"<="    return LE;
"<"     return LT;
">="    return GE;
">"     return GT;
"=="    return EQ;
"!="    return NE;
"||"    return OR;
"&&"    return AND;
"+"     return ADD;
"-"     return SUB;
"*"     return MUL;
"/"     return DIV;
.    return yytext[0];
%%
---------------------------------------------------------
Output:
sakshi@sakshi-hp-Z510:~$ lex switch.l
sakshi@sakshi-hp-Z510:~$ yacc -d switch.y
sakshi@sakshi-hp-Z510:~$ gcc y.tab.c -ll -ly
sakshi@sakshi-hp-Z510:~$ ./a.out
Enter the expression: switch(a)
{
 case 1:a=3;
     break;
 default:a=9+7;
}
parse error
sakshi@sakshi-hp-Z510:~$ ./a.out
Enter the expression: switch(a)
{
 case 1:a=4+3;
        break;
 case 2:a=12/6;
        break;
 default:a=3*8;
        break;
}
Input accepted.
sakshi@sakshi-hp-Z510:~$ 


